package com.itheima.server.service;

import com.itheima.autoconfig.template.AipFaceTemplate;
import com.itheima.autoconfig.template.OssTemplate;
import com.itheima.dubbo.api.UserInfoApi;
import com.itheima.model.domain.UserInfo;
import com.itheima.model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //上传头像到aliyun

        String upload = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //将返回地址给百度人脸识别判断头像是否合法（是人脸）
        if (!aipFaceTemplate.detect(upload)) {
            throw new RuntimeException("你不是人");
            //不合法就抛出异常
        }
        //合法就调用api更新操作
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(upload);
        userInfoApi.update(userInfo);

    }

    /*查看个人资料封装返回值对象
     * */
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    /*更新个人资料
     * */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
